#ifndef HYBRID_RPC_SERVER_HPP
#define HYBRID_RPC_SERVER_HPP

#include <zmq.h>
#include <nlohmann/json.hpp>
#include <unordered_map>
#include <functional>
#include <atomic>
#include <string>
#include <set>
#include <mutex>

using json = nlohmann::json;

class HybridRPCServer
{
  public:
    HybridRPCServer (const std::string &rpc_bind_addr,
                     const std::string &stream_bind_addr);
    ~HybridRPCServer ();

    void registerMethod (const std::string &name,
                         std::function<json (const json &)> func);
    void start ();
    void stop ();

  private:
    void runEventLoop ();
    void handleRPCMessage ();
    void handleStreamMessage ();
    std::string processRPCRequest (const std::string &request);
    void sendStreamResponse (const std::string &client_id,
                             const std::string &data);

    void *ctx_;
    void *rpc_socket_;
    void *stream_socket_;

    std::unordered_map<std::string, std::function<json (const json &)> >
      methods_;
    std::set<std::string> connected_streams_;
    std::mutex streams_mutex_;

    std::unique_ptr<std::thread> worker_thread_; // 使用智能指针管理线程
    std::atomic<bool> running_{false};           // 原子标志位
    std::mutex thread_mutex_;                    // 线程操作互斥锁
};

#endif // HYBRID_RPC_SERVER_HPP